<?php

namespace App\Services\AliyunSMS;

use Config;
use Log;
use Aliyun\Core\Profile\DefaultProfile;
use Aliyun\Core\DefaultAcsClient;
use Aliyun\Core\Sms\Request\V20160927\SingleSendSmsRequest;
use Aliyun\Core\Exception\ClientException;
use Aliyun\Core\Exception\ServerException;
use Aliyun\Core\Regions\Endpoint;
use Aliyun\Core\Regions\EndpointProvider;
use Aliyun\Core\Regions\EndpointConfig;

class SmsService
{
	private $client;

	public function __construct()
	{	
		$accessKeyId     = Config::get('app.oss.accessKeyId');
		$accessKeySecret = Config::get('app.oss.accessKeySecret');
		$iClientProfile = DefaultProfile::getProfile('cn-hangzhou', $accessKeyId, $accessKeySecret);
		$this->client = new DefaultAcsClient($iClientProfile);
	}

	public static function send($SignName, $templateCode, $recNum, $paramString)
	{
		$sms = new SmsService();
		$config = new EndpointConfig();
		$endpoint = new Endpoint('cn-hangzhou', $config->getRegionIds(), $config->getProductDomains());
		$endpoints = array( $endpoint );
		EndpointProvider::setEndpoints($endpoints);
		$request = new SingleSendSmsRequest();
    	$request->setSignName($SignName);/*签名名称*/
    	$request->setTemplateCode($templateCode);/*模板code*/
    	$request->setRecNum($recNum);/*目标手机号*/
    	$request->setParamString($paramString);/*模板变量，数字一定要转换为字符串*/

    	try {
        	$response = $sms->client->getAcsResponse($request);
        	return true;
        	// dd($response);
	    }
	    catch (ClientException  $e) {
	    	Log::error('aliyun sms error: '.$e->getErrorCode());
	    	Log::error('aliyun sms error: '.$e->getErrorMessage());
	    }
	    catch (ServerException  $e) {
	    	Log::error('aliyun sms error: '.$e->getErrorCode());
	    	Log::error('aliyun sms error: '.$e->getErrorMessage());    
	    }
	}
}